<?php

namespace App\Http\Controllers\Admin\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use App\Models\Customer;
use App\Models\Charge;
use App\Services\Utils\Guard;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;
use App\Exceptions\ApiAbstractException;
use App\Exceptions\ApiErrCode;

class ChargeController extends ApiController
{
    public function charges(Request $request)
    {
        $where = $this->getWhere($request->only('start_time', 'end_time'));

        $user = Guard::customer();
        $where['customer_id'] = $user['id'];
        
        $balance = Charge::where('customer_id', $user['id'])->latest()->value('change_after')/100.0;
        $charges = Charge::where($where)->latest()->paginate($request->per_page);
        foreach ($charges as $value) {
            $value['change_before'] = $value['change_before']/100.0;
            $value['change_after'] = $value['change_after']/100.0;
        }
        return $this->response(compact('balance', 'charges'));
    }

    //todo 需添加模型过滤
    public function getWhere($filter_data)
    {
        $where = [];
        
        if(!empty($filter_data->start_time)){
            $where[] = ['created_at', '>=', $filter_data->start_time];
        }
        if(!empty($filter_data->end_time)){
            $where[] = ['created_at', '<=', $filter_data->end_time];
        }
        
        return $where;
    }
}
